Page({
  data: {
    // 筛选和排序状态
    brandFilter: 'tesla',
    sortType: 'default',
    refresherTriggered: false,
    
    // 品牌下拉相关状态
    showBrandDropdown: false,
    selectedBrandLabel: '特斯拉',
    
    // 品牌选择弹窗状态
    showBrandModal: false,
    
    // 所有品牌数据（包含图片）
    allBrands: [],
    brandDataLoaded: false,
    
    // 品牌筛选选项
    brandOptions: [
      { label: '全部品牌', value: 'all', icon: '🏷️' },
      { label: '特斯拉', value: 'tesla', icon: '🚗' },
      { label: '蔚来', value: 'nio', icon: '🔋' },
      { label: '小鹏', value: 'xpeng', icon: '✨' },
      { label: '比亚迪', value: 'byd', icon: '🌿' },
      { label: '理想', value: 'lixiang', icon: '💫' }
    ],
    
    // 分页参数
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    
    // 车辆数据
    cars: [],
    
    // 完整车辆数据库
    carDatabase: [
      {
        id: 1,
        name: 'Model 3 2022款后轮驱动版',
        year: '2022年',
        mileage: '1.27万公里',
        location: 'EAP',
        city: '重庆',
        price: '26.18',
        downPayment: '5.68',
        image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        isHot: true,
        isSelected: false,
        isBooked: true,
        tags: ['准新车', '0过户'],
        brand: 'tesla'
      },
      {
        id: 2,
        name: 'Model S 2017款75D 标准续航版',
        year: '2016年',
        mileage: '2.27万公里',
        location: 'EAP',
        city: '重庆',
        price: '37.56',
        downPayment: '7.15',
        image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
        isHot: false,
        isSelected: true,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'tesla'
      },
      {
        id: 3,
        name: 'ES6 2020款 420KM 运动版',
        year: '2021年',
        mileage: '0.05万公里',
        location: 'EAP',
        city: '重庆',
        price: '37.56',
        downPayment: '7.15',
        image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
        isHot: false,
        isSelected: true,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'nio'
      },
      {
        id: 4,
        name: '汉 2021款 EV 标准续航版豪华型',
        year: '2021年',
        mileage: '0.05万公里',
        location: 'EAP',
        city: '重庆',
        price: '19.02',
        downPayment: '4.55',
        image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        isHot: false,
        isSelected: true,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'byd'
      },
      {
        id: 5,
        name: 'Model Y 2022款长续航版',
        year: '2022年',
        mileage: '0.8万公里',
        location: 'EAP',
        city: '重庆',
        price: '42.88',
        downPayment: '8.58',
        image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
        isHot: true,
        isSelected: false,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'tesla'
      },
      {
        id: 6,
        name: 'P7 2023款智享版',
        year: '2022年',
        mileage: '1.2万公里',
        location: 'EAP',
        city: '重庆',
        price: '25.58',
        downPayment: '5.12',
        image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
        isHot: false,
        isSelected: true,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'xpeng'
      },
      {
        id: 7,
        name: 'ONE 2022款增程版',
        year: '2021年',
        mileage: '2.5万公里',
        location: 'EAP',
        city: '重庆',
        price: '28.88',
        downPayment: '5.78',
        image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        isHot: false,
        isSelected: true,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'lixiang'
      },
      {
        id: 8,
        name: 'ET7 2023款首发版',
        year: '2022年',
        mileage: '0.5万公里',
        location: 'EAP',
        city: '重庆',
        price: '42.80',
        downPayment: '8.56',
        image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
        isHot: true,
        isSelected: false,
        isBooked: false,
        tags: ['准新车', '0过户'],
        brand: 'nio'
      }
    ]
  },

  // 页面生命周期
  onLoad: function (options) {
    console.log('买车页面加载完成', options);
    
    // 检查是否有品牌参数传入
    if (options.brand && options.brandName) {
      const brandValue = options.brand;
      const brandName = decodeURIComponent(options.brandName);
      
      console.log('接收到品牌参数:', brandValue, brandName);
      
      this.setData({
        brandFilter: brandValue,
        selectedBrandLabel: brandName,
        page: 1,
        cars: [],
        hasMore: true
      });
    }
    
    this.loadBrandData();
    this.loadCarsFromAPI();
  },

  onShow: function () {
    console.log('买车页面显示');
    
    // 检查全局数据中是否有品牌信息
    const app = getApp();
    if (app.globalData && app.globalData.selectedBrand) {
      const brandInfo = app.globalData.selectedBrand;
      console.log('从全局数据获取品牌信息:', brandInfo);
      
      // 更新品牌筛选，使用品牌ID进行筛选
      this.setData({
        brandFilter: brandInfo.value,
        selectedBrandLabel: brandInfo.name,
        page: 1,
        cars: [],
        hasMore: true,
        showBrandDropdown: false
      });
      
      // 如果有品牌ID，将其存储用于API请求
      if (brandInfo.id) {
        this.selectedBrandId = brandInfo.id;
      }
      
      // 清除全局数据中的品牌信息
      app.globalData.selectedBrand = null;
      
      // 加载对应品牌的车辆数据
      this.loadCarsFromAPI();
      
      // 显示设置成功提示
      wx.showToast({
        title: `已切换到${brandInfo.name}`,
        icon: 'success',
        duration: 1500
      });
    }
    
    // 检查是否有待处理的品牌筛选（兼容旧逻辑）
    if (this.pendingBrandFilter) {
      const { brandValue, brandName } = this.pendingBrandFilter;
      this.setBrandFilter(brandValue, brandName);
      this.pendingBrandFilter = null;
    }
  },

  // 加载品牌数据
  loadBrandData: function(retryCount = 0) {
    console.log('开始加载品牌数据...', retryCount > 0 ? `(重试第${retryCount}次)` : '');
    
    wx.request({
      url: 'http://localhost:6001/carBrand/findAll',
      method: 'GET',
      timeout: 10000, // 10秒超时
      success: (res) => {
        console.log('品牌数据加载成功:', res.data);
        if (res.data && Array.isArray(res.data) && res.data.length > 0) {
          // 更新所有品牌数据（用于弹窗显示）
          this.setData({
            allBrands: res.data,
            brandDataLoaded: true
          });
          
          // 同时更新下拉选择的品牌选项，保留"全部品牌"选项
          const dynamicBrandOptions = [
            { label: '全部品牌', value: 'all', icon: '🏷️' },
            ...res.data.map(brand => ({
              label: brand.brandName,
              value: brand.brandName.toLowerCase().replace(/\s+/g, ''),
              icon: '🚗',
              brandLogo: brand.brandLogo
            }))
          ];
          
          this.setData({
            brandOptions: dynamicBrandOptions
          });
          
          console.log('品牌选项更新完成:', dynamicBrandOptions);
          
          // 显示成功提示（仅在重试成功时显示）
          if (retryCount > 0) {
            wx.showToast({
              title: '品牌数据加载成功',
              icon: 'success',
              duration: 1500
            });
          }
        } else {
          throw new Error('品牌数据为空或格式错误');
        }
      },
      fail: (err) => {
        console.error('品牌数据加载失败:', err);
        
        // 重试逻辑（最多重试2次）
        if (retryCount < 2) {
          setTimeout(() => {
            this.loadBrandData(retryCount + 1);
          }, 2000 * (retryCount + 1)); // 递增延迟
          
          wx.showToast({
            title: `加载失败，${2 - retryCount}秒后重试`,
            icon: 'none',
            duration: 1500
          });
        } else {
          // 最终失败处理
          this.setData({
            brandDataLoaded: false
          });
          
          wx.showModal({
            title: '网络错误',
            content: '品牌数据加载失败，是否重新加载？',
            confirmText: '重新加载',
            cancelText: '使用默认',
            success: (res) => {
              if (res.confirm) {
                this.loadBrandData(0);
              } else {
                console.log('使用静态品牌数据作为备用');
                wx.showToast({
                  title: '已切换到默认品牌',
                  icon: 'none',
                  duration: 1500
                });
              }
            }
          });
        }
      }
    });
  },

  // 点击照片显示品牌选择弹窗
  showBrandSelection: function() {
    this.setData({
      showBrandModal: true
    });
  },

  // 关闭品牌选择弹窗
  closeBrandModal: function() {
    this.setData({
      showBrandModal: false
    });
  },

  // 从品牌弹窗中选择品牌
  selectBrandFromModal: function(e) {
    var brand = e.currentTarget.dataset.brand;
    console.log('从弹窗选择品牌：', brand);
    
    // 根据品牌名称查找对应的品牌选项
    var brandValue = brand.brandName.toLowerCase().replace(/\s+/g, '');
    
    // 存储品牌ID用于API请求
    this.selectedBrandId = brand.id;
    
    this.setData({
      brandFilter: brandValue,
      selectedBrandLabel: brand.brandName,
      showBrandModal: false,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
    
    wx.showToast({
      title: `已选择${brand.brandName}`,
      icon: 'success',
      duration: 1500
    });
  },

  // 选择全部品牌
  selectAllBrands: function() {
    console.log('选择全部品牌');
    
    // 清除存储的品牌ID
    this.selectedBrandId = null;
    
    this.setData({
      brandFilter: 'all',
      selectedBrandLabel: '全部品牌',
      showBrandModal: false,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
    
    wx.showToast({
      title: '已选择全部品牌',
      icon: 'success',
      duration: 1500
    });
  },

  // 品牌图片加载失败处理
  onBrandImageError: function(e) {
    console.warn('品牌图片加载失败:', e.detail);
    // 可以在这里设置默认图片或其他处理逻辑
  },

  // 从下拉菜单选择品牌
  selectBrandFromDropdown: function(e) {
    var brand = e.currentTarget.dataset.brand;
    console.log('从下拉菜单选择品牌：', brand);
    
    var brandValue = brand.brandName.toLowerCase().replace(/\s+/g, '');
    
    // 存储品牌ID用于API请求
    this.selectedBrandId = brand.id;
    
    this.setData({
      brandFilter: brandValue,
      selectedBrandLabel: brand.brandName,
      showBrandDropdown: false,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
    
    wx.showToast({
      title: `已选择${brand.brandName}`,
      icon: 'success',
      duration: 1500
    });
  },

  // 设置品牌筛选（供其他页面调用）
  setBrandFilter: function(brandValue, brandName) {
    console.log('设置品牌筛选:', brandValue, brandName);
    console.log('当前品牌选项:', this.data.brandOptions);
    
    // 验证品牌值是否有效
    const validBrand = this.data.brandOptions.find(option => option.value === brandValue);
    if (!validBrand && brandValue !== 'all') {
      console.warn('无效的品牌值:', brandValue);
      return;
    }
    
    this.setData({
      brandFilter: brandValue,
      selectedBrandLabel: brandName,
      page: 1,
      cars: [],
      hasMore: true,
      showBrandDropdown: false // 确保下拉菜单关闭
    });
    
    console.log('品牌筛选设置完成，开始加载数据...');
    this.loadCarsFromAPI();
  },

  // 加载车辆数据
  // 从后端API获取车辆数据
  loadCarsFromAPI: function() {
    console.log('从后端API加载车辆数据...');
    
    var self = this;
    
    // 显示加载状态
    this.setData({
      loading: true
    });
    
    // 准备请求参数 - 修正品牌ID传递逻辑
    var brandId = null;
    if (this.data.brandFilter && this.data.brandFilter !== 'all') {
      // 优先使用存储的品牌ID
      if (this.selectedBrandId) {
        brandId = this.selectedBrandId.toString();
      } else {
        // 如果没有存储的品牌ID，通过品牌名称查找
        const selectedBrand = this.data.allBrands.find(brand => 
          brand.brandName.toLowerCase().replace(/\s+/g, '') === this.data.brandFilter
        );
        if (selectedBrand) {
          brandId = selectedBrand.id.toString();
        }
      }
    }
    
    var requestData = {
      page: this.data.page,
      pageSize: this.data.pageSize,
      brandId: brandId,
      sortType: this.data.sortType
    };
    
    console.log('=== API请求调试信息 ===');
    console.log('当前品牌筛选:', this.data.brandFilter);
    console.log('存储的品牌ID:', this.selectedBrandId);
    console.log('最终传递的品牌ID:', brandId);
    console.log('完整请求参数:', requestData);
    console.log('========================');
    
    wx.request({
      url: 'http://localhost:6002/carInfo/findList',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: requestData,
      success: function(res) {
        console.log('API请求成功:', res.data);
        
        if (res.data && res.data.code === 200) {
          // 处理成功响应
          self.handleAPISuccess(res.data.data || []);
        } else {
          console.error('API返回错误:', res.data);
          self.handleAPIError(res.data.message || '获取数据失败');
        }
      },
      fail: function(error) {
        console.error('API请求失败:', error);
        self.handleAPIError('网络请求失败，使用本地数据');
        // 网络失败时使用本地数据
        self.loadCarData();
      },
      complete: function() {
        self.setData({
          loading: false,
          refresherTriggered: false
        });
      }
    });
  },
  
  // 处理API成功响应
  handleAPISuccess: function(carList) {
    console.log('处理API数据:', carList);
    
    // 转换后端数据格式为前端显示格式
    var formattedCars = carList.map(function(car, index) {
      console.log(`车辆${index + 1} - ID: ${car.id}, 原始价格:`, car.price, '类型:', typeof car.price);
      
      // 计算首付（假设首付为总价的20%）
      var priceNum = parseFloat(car.price || 0);
      var downPayment = (priceNum * 0.2 / 10000).toFixed(2); // 转换为万元
      var priceWan = (priceNum / 10000).toFixed(2); // 转换为万元
      
      console.log(`车辆${index + 1} - 转换后价格(万元):`, priceWan, '首付:', downPayment);
      
      return {
        id: car.id || index + 1,
        name: car.modelName || '未知车型',
        year: car.registerTime ? new Date(car.registerTime).getFullYear() + '年' : '未知年份',
        mileage: car.mileage ? car.mileage + '万公里' : '0万公里',
        location: 'EAP',
        city: '重庆', // 固定城市，可根据需要修改
        price: priceWan,
        downPayment: downPayment,
        image: car.mainPic || 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        isHot: Math.random() > 0.7, // 随机设置热门标签
        isSelected: Math.random() > 0.5, // 随机设置精选标签
        isBooked: car.status === 2, // 已售出的显示为已预订
        tags: car.status === 1 ? ['在售', '质检通过'] : ['已售出'],
        brand: car.brandId || 'unknown',
        brandName: '未知品牌', // 这里需要通过品牌ID查找品牌名称
        displacement: car.displacement ? car.displacement + 'L' : '未知',
        color: car.color || '未知颜色',
        registerTime: car.registerTime,
        carCondition: car.carCondition,
        fuelType: car.fuelType,
        gearboxType: car.gearboxType,
        originalData: car // 保存原始数据
      };
    });
    
    // 根据页数决定是追加还是替换数据
    if (this.data.page === 1) {
      this.setData({
        cars: formattedCars,
        hasMore: formattedCars.length >= this.data.pageSize
      });
    } else {
      this.setData({
        cars: this.data.cars.concat(formattedCars),
        hasMore: formattedCars.length >= this.data.pageSize
      });
    }
    
    console.log('车辆数据更新完成，共', this.data.cars.length, '辆车');
  },
  
  // 处理API错误
  handleAPIError: function(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  },

  // 数据加载相关方法（保留作为备用）
  loadCarData: function () {
    console.log('开始加载车辆数据...');
    
    const { page, pageSize, carDatabase, brandFilter, sortType } = this.data;
    
    // 筛选数据
    let filteredCars = this.filterCarsByBrand(carDatabase, brandFilter);
    
    // 排序数据
    filteredCars = this.sortCars(filteredCars, sortType);
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const newCars = filteredCars.slice(startIndex, endIndex);
    
    console.log(`加载第${page}页，共${newCars.length}辆车`);
    
    this.setData({
      cars: newCars,
      hasMore: endIndex < filteredCars.length
    });
  },

  // 排序车辆数据
  sortCars: function(cars, sortType) {
    switch (sortType) {
      case 'price':
        return cars.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
      case 'mileage':
        return cars.sort((a, b) => parseFloat(a.mileage) - parseFloat(b.mileage));
      case 'location':
        return cars.sort((a, b) => a.city.localeCompare(b.city));
      default:
        return cars;
    }
  },

  // 筛选车辆数据
  filterCarsByBrand: function(cars, brandFilter) {
    if (brandFilter === 'all') {
      return cars;
    }
    
    // 处理品牌筛选 - 支持动态品牌数据
    return cars.filter(car => {
      // 精确匹配
      if (car.brand === brandFilter) {
        return true;
      }
      
      // 模糊匹配品牌名称（处理大小写和空格）
      const carBrandNormalized = car.brand.toLowerCase().replace(/\s+/g, '');
      const filterNormalized = brandFilter.toLowerCase().replace(/\s+/g, '');
      
      return carBrandNormalized === filterNormalized;
    });
  },

  // 加载更多车辆
  loadMoreCars: function () {
    console.log('开始加载更多车辆');
    
    if (this.data.loading || !this.data.hasMore) {
      return;
    }
    
    // 增加页数并重新请求API
    this.setData({
      page: this.data.page + 1
    });
    
    this.loadCarsFromAPI();
  },

  // scroll-view 下拉刷新
  onRefresherRefresh: function () {
    if (this.data.refresherTriggered) return;
    
    console.log('下拉刷新触发');
    
    this.setData({ 
      refresherTriggered: true, 
      page: 1, 
      cars: [], 
      hasMore: true, 
      loading: false 
    });
    
    // 使用API重新加载数据
    this.loadCarsFromAPI();
    
    wx.showToast({ title: '刷新成功', icon: 'success' });
  },

  // scroll-view 触底加载
  onScrollToLower: function () {
    if (this.data.loading || !this.data.hasMore) return;
    this.loadMoreCars();
  },

  // 切换品牌下拉菜单
  toggleBrandDropdown: function() {
    this.setData({
      showBrandDropdown: !this.data.showBrandDropdown
    });
  },

  // 关闭品牌下拉菜单
  closeBrandDropdown: function() {
    this.setData({
      showBrandDropdown: false
    });
  },

  // 阻止事件冒泡
  stopPropagation: function() {
    // 空函数，用于阻止事件冒泡
  },

  // 选择品牌
  selectBrand: function(e) {
    var brand = e.currentTarget.dataset.brand;
    console.log('选择品牌:', brand);
    
    // 存储品牌ID用于API请求（如果有的话）
    if (brand.id) {
      this.selectedBrandId = brand.id;
    } else {
      // 对于静态品牌选项，通过品牌名称查找ID
      const foundBrand = this.data.allBrands.find(b => 
        b.brandName.toLowerCase().replace(/\s+/g, '') === brand.value
      );
      if (foundBrand) {
        this.selectedBrandId = foundBrand.id;
      } else {
        this.selectedBrandId = null;
      }
    }
    
    this.setData({
      brandFilter: brand.value,
      selectedBrandLabel: brand.label,
      showBrandDropdown: false,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
  },

  // 品牌筛选（保持兼容性）
  selectBrandFilter: function(e) {
    var value = e.currentTarget.dataset.value;
    console.log('选择品牌筛选:', value);
    
    // 通过品牌值查找对应的品牌ID
    if (value === 'all') {
      this.selectedBrandId = null;
    } else {
      const foundBrand = this.data.allBrands.find(b => 
        b.brandName.toLowerCase().replace(/\s+/g, '') === value
      );
      if (foundBrand) {
        this.selectedBrandId = foundBrand.id;
        console.log('找到品牌ID:', foundBrand.id, '品牌名称:', foundBrand.brandName);
      } else {
        this.selectedBrandId = null;
        console.warn('未找到对应的品牌ID，value:', value);
      }
    }
    
    this.setData({
      brandFilter: value,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
  },

  // 排序选择
  selectSort: function(e) {
    var type = e.currentTarget.dataset.type;
    console.log('选择排序:', type);
    
    this.setData({
      sortType: type,
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
  },

  // 查看车辆详情
  viewCarDetail: function(e) {
    const car = e.currentTarget.dataset.car;
    console.log('查看车辆详情:', car);
    
    // 跳转到商品详情页面
    wx.navigateTo({
      url: `/pages/car-detail/car-detail?id=${car.id}`
    });
  },

  // 搜索功能
  onSearch: function() {
    wx.showToast({
      title: '搜索功能开发中',
      icon: 'none'
    });
  },

  // 高级筛选
  onAdvancedFilter: function() {
    wx.showActionSheet({
      itemList: ['价格区间', '车龄筛选', '里程筛选', '所在地区', '重置筛选'],
      success: (res) => {
        const actions = ['价格区间', '车龄筛选', '里程筛选', '所在地区', '重置筛选'];
        if (res.tapIndex === 4) {
          // 重置筛选
          this.resetFilters();
        } else {
          wx.showToast({
            title: `选择了${actions[res.tapIndex]}`,
            icon: 'none'
          });
        }
      }
    });
  },

  // 重置筛选条件
  resetFilters: function() {
    this.setData({
      brandFilter: 'all',
      selectedBrandLabel: '全部品牌',
      sortType: 'default',
      page: 1,
      cars: [],
      hasMore: true
    });
    
    this.loadCarsFromAPI();
    
    wx.showToast({
      title: '已重置筛选条件',
      icon: 'success'
    });
  }
});
